#include <Servo.h>
#include <Wire.h>
#include "SSD1306.h"
#include <DS3231.h>
#include "DHT.h"
#include "BluetoothSerial.h"

#define DHTTYPE DHT11
#define DHTPIN 5
SSD1306 display(0x3c, 21, 22);
DS3231 Clock;
DHT dht(DHTPIN, DHTTYPE);
BluetoothSerial SerialBT;
char START_FLAG = '$';
char END_FLAG = '#';

int pin1 = 23;
Servo servo1;
int k1;
int k2;
int k3;
int a = 200;
bool h12;
bool PM;
int zt = 0;
String zkb = "speed:" + String(a);
int NONE = 0;
int START = 1;
int pre_status = NONE;
int num;

void SerialBT_sendMsg(String msg) {
  int i = 0;
  for (i = 0; i < msg.length(); i++) {
    SerialBT.write(msg[i]);
  }
}

void zd() {
  a = 200;
  servo1.write(int(a / 10));
  while (SerialBT.available()) {
    Serial.println("stop");
    char msg_char = SerialBT.read();
    delay(1000);
  }
  SerialBT_sendMsg("$" + String(a) + "#");
}

void setup() {
  SerialBT.begin("风扇");
  servo1.attach(pin1);
  pinMode(15, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
  attachInterrupt(2,zd,RISING);
  Serial.begin(9600);
  Serial.print("welcome");
  display.init();
  display.setFont(ArialMT_Plain_24);
  display.drawString(0, 0, "welcome");
  display.display();
  Wire.begin();
  dht.begin();
  delay(500);
  servo1.write(0);
  display.clear();
  display.setFont(ArialMT_Plain_16);
}

void loop() {
  k1 = digitalRead(15);
  k3 = digitalRead(4);
  if (k1 == HIGH)zt = 1;
  if (k3 == HIGH)zt = 3;

  display.clear();
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  String tp = "H:" + String(h) + "T:" + String(t);
  String tim = String(Clock.getHour(h12, PM)) + ':' + String(Clock.getMinute());
  display.drawString(0, 0,  zkb);
  display.drawString(0, 20, tim);
  display.drawString(0, 40, tp);
  display.display();

  switch (zt) {
    case 1:
      a = a - 10;
      if (a <= 200) {
        a = 200;
      }
      SerialBT_sendMsg("$" + String(a) + "#");
      break;

    case 3:
      a = a + 10;
      if (a >= 1500) {
        a = 1500;
      }
      SerialBT_sendMsg("$" + String(a) + "#");
      break;


  }
  if (SerialBT.available()) {
    Serial.println("bl get");
    char msg_char = SerialBT.read();
    Serial.println(msg_char);
    if (msg_char == START_FLAG) {
      pre_status = START;
    } else if (msg_char == END_FLAG && pre_status == START) {
      String msg = String("get data \n");
      SerialBT_sendMsg(String(num));
      a = num;
      num = 0;
      if (a <= 200) {
        a = 200;
      }
      if (a >= 1500) {
        a = 1500;
      }
      servo1.write(int(a / 10));
      pre_status = NONE;
    } else if (isDigit(msg_char) && pre_status == START) {
      num = num * 10 + (msg_char - '0');
      SerialBT_sendMsg(String(String(msg_char) + "\n"));
    } else {
      pre_status = NONE;
    }
  }
  zkb = "speed:" + String(a);
  servo1.write(int(a / 10));
  zt = 0;
  delay(50);
}
